Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [1]:
# The new version of dataset is only available in the tfds-nightly package.
%pip --no-cache-dir install tfds-nightly --user 
!pip install tensorflow --upgrade --user
%pip --no-cache-dir install tensorflow-datasets --user
# DON'T MISS TO RESTART THE KERNEL
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/0a/87/94d83e57c5b32920a2975697499a416fd7567001870acdac14cec1989eb2/tfds_nightly-4.2.0.dev202104300107-py3-none-any.whl (3.8MB)
     |████████████████████████████████| 3.9MB 5.9MB/s eta 0:00:01
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/60/7a/e881b5abb54db0e6e671ab088d079c57ce54e8a01a3ca443f561ccadb37e/typing_extensions-3.7.4.3-py3-none-any.whl
Requirement already satisfied: attrs>=18.1.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (19.3.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/51/4e/de63de3cd9a83d3c1753a4566b11fc9d90b845f2448a132cfd36d3cb3cd1/protobuf-3.15.8-cp37-cp37m-manylinux1_x86_64.whl (1.0MB)
     |████████████████████████████████| 1.0MB 34.4MB/s eta 0:00:01
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/f0/5e/69e6a0602c1f18d390952177de648468c4a380252858b0022affc3ce7811/importlib_resources-5.1.2-py3-none-any.whl
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: zipp>=0.4; python_version < "3.8" in /opt/conda/lib/python3.7/site-packages (from importlib-resources; python_version < "3.9"->tfds-nightly) (0.6.0)
Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from zipp>=0.4; python_version < "3.8"->importlib-resources; python_version < "3.9"->tfds-nightly) (8.0.2)
Installing collected packages: typing-extensions, protobuf, importlib-resources, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed importlib-resources-5.1.2 protobuf-3.15.8 tfds-nightly-4.2.0.dev202104300107 typing-extensions-3.7.4.3
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/70/dc/e8c5e7983866fa4ef3fd619faa35f660b95b01a2ab62b3884f038ccab542/tensorflow-2.4.1-cp37-cp37m-manylinux2010_x86_64.whl (394.3MB)
     |████████████████████████████████| 394.3MB 30kB/s s eta 0:00:01     |█████████▉                      | 120.7MB 28.9MB/s eta 0:00:10
Collecting numpy~=1.19.2
  Downloading https://files.pythonhosted.org/packages/08/d6/a6aaa29fea945bc6c61d11f6e0697b325ff7446de5ffd62c2fa02f627048/numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8MB)
     |████████████████████████████████| 14.8MB 26.6MB/s eta 0:00:01
Collecting tensorflow-estimator<2.5.0,>=2.4.0
  Downloading https://files.pythonhosted.org/packages/74/7e/622d9849abf3afb81e482ffc170758742e392ee129ce1540611199a59237/tensorflow_estimator-2.4.0-py2.py3-none-any.whl (462kB)
     |████████████████████████████████| 471kB 22.2MB/s eta 0:00:01
Collecting h5py~=2.10.0
  Downloading https://files.pythonhosted.org/packages/3f/c0/abde58b837e066bca19a3f7332d9d0493521d7dd6b48248451a9e3fe2214/h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9MB)
     |████████████████████████████████| 2.9MB 37.3MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: typing-extensions~=3.7.4 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.7.4.3)
Collecting tensorboard~=2.4
  Downloading https://files.pythonhosted.org/packages/44/f5/7feea02a3fb54d5db827ac4b822a7ba8933826b36de21880518250b8733a/tensorboard-2.5.0-py3-none-any.whl (6.0MB)
     |████████████████████████████████| 6.0MB 32.9MB/s eta 0:00:01
Collecting six~=1.15.0
  Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting grpcio~=1.32.0
  Downloading https://files.pythonhosted.org/packages/06/54/1c8be62beafe7fb1548d2968e518ca040556b46b0275399d4f3186c56d79/grpcio-1.32.0-cp37-cp37m-manylinux2014_x86_64.whl (3.8MB)
     |████████████████████████████████| 3.8MB 31.5MB/s eta 0:00:01
Collecting absl-py~=0.10
  Downloading https://files.pythonhosted.org/packages/92/c9/ef0fae29182d7a867d203f0eff8296b60da92098cc41db33a434f4be84bf/absl_py-0.12.0-py3-none-any.whl (129kB)
     |████████████████████████████████| 133kB 40.0MB/s eta 0:00:01
Collecting gast==0.3.3
  Downloading https://files.pythonhosted.org/packages/d6/84/759f5dd23fec8ba71952d97bcc7e2c9d7d63bdc582421f3cd4be845f0c98/gast-0.3.3-py2.py3-none-any.whl
Collecting opt-einsum~=3.3.0
  Downloading https://files.pythonhosted.org/packages/bc/19/404708a7e54ad2798907210462fd950c3442ea51acc8790f3da48d2bee8b/opt_einsum-3.3.0-py3-none-any.whl (65kB)
     |████████████████████████████████| 71kB 9.1MB/s  eta 0:00:01
Collecting wheel~=0.35
  Downloading https://files.pythonhosted.org/packages/65/63/39d04c74222770ed1589c0eaba06c05891801219272420b40311cd60c880/wheel-0.36.2-py2.py3-none-any.whl
Collecting wrapt~=1.12.1
  Downloading https://files.pythonhosted.org/packages/82/f7/e43cefbe88c5fd371f4cf0cf5eb3feccd07515af9fd6cf7dbf1d1793a797/wrapt-1.12.1.tar.gz
Requirement already satisfied, skipping upgrade: protobuf>=3.9.2 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.15.8)
Collecting google-pasta~=0.2
  Downloading https://files.pythonhosted.org/packages/a3/de/c648ef6835192e6e2cc03f40b19eeda4382c49b5bafb43d88b931c4c74ac/google_pasta-0.2.0-py3-none-any.whl (57kB)
     |████████████████████████████████| 61kB 9.4MB/s  eta 0:00:01
Requirement already satisfied, skipping upgrade: termcolor~=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Collecting astunparse~=1.6.3
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting flatbuffers~=1.12.0
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting keras-preprocessing~=1.1.2
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 8.1MB/s  eta 0:00:01
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (41.4.0)
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/12/63/d92b4bc44261b7396558c054f78acf71468b5628bcb14cdaeb2504ea80d3/tensorboard_data_server-0.6.0-py3-none-manylinux2010_x86_64.whl (3.9MB)
     |████████████████████████████████| 3.9MB 39.3MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (0.16.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/1a/c1/499e600ba0c618b451cd9c425ae1c177249940a2086316552fee7d86c954/tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 16.8MB/s eta 0:00:01
Collecting google-auth<2,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/d2/c1/44179a1cfc5c3b5832a5f9c925161612471ec5f346bcd186235651d74f35/google_auth-1.30.0-py2.py3-none-any.whl (146kB)
     |████████████████████████████████| 153kB 28.5MB/s eta 0:00:01
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/9d/d3/7541e89f1fc456eef157224f597a8bba22589db6369a03eaba68c11f07a0/google_auth_oauthlib-0.4.4-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (3.1.1)
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow) (2.22.0)
Collecting cachetools<5.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/bf/28/c4f5796c67ad06bb91d98d543a5e01805c1ff065e08871f78e52d2a331ad/cachetools-4.2.2-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 29.2MB/s eta 0:00:01
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/e9/93/0c0f002031f18b53af7a6166103c02b9c0667be528944137cc954ec921b3/rsa-4.7.2-py3-none-any.whl
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2019.11.28)
Collecting pyasn1<0.5.0,>=0.4.6
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 12.5MB/s eta 0:00:01
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/05/57/ce2e7a8fa7c0afb54a0581b14a65b56e62b5759dbc98e80627142b8a3704/oauthlib-3.1.0-py2.py3-none-any.whl (147kB)
     |████████████████████████████████| 153kB 38.9MB/s eta 0:00:01
Building wheels for collected packages: wrapt
  Building wheel for wrapt (setup.py) ... done
  Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=70990 sha256=0686c39ce23f4f82a1e476cc753164c267526b73960ac6edaecfcf0bd7b142c7
  Stored in directory: /root/.cache/pip/wheels/b1/c2/ed/d62208260edbd3fa7156545c00ef966f45f2063d0a84f8208a
Successfully built wrapt
Installing collected packages: numpy, tensorflow-estimator, six, h5py, wheel, grpcio, tensorboard-data-server, tensorboard-plugin-wit, absl-py, cachetools, pyasn1, pyasn1-modules, rsa, google-auth, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard, gast, opt-einsum, wrapt, google-pasta, astunparse, flatbuffers, keras-preprocessing, tensorflow
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script wheel is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-0.12.0 astunparse-1.6.3 cachetools-4.2.2 flatbuffers-1.12 gast-0.3.3 google-auth-1.30.0 google-auth-oauthlib-0.4.4 google-pasta-0.2.0 grpcio-1.32.0 h5py-2.10.0 keras-preprocessing-1.1.2 numpy-1.19.5 oauthlib-3.1.0 opt-einsum-3.3.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.7.2 six-1.15.0 tensorboard-2.5.0 tensorboard-data-server-0.6.0 tensorboard-plugin-wit-1.8.0 tensorflow-2.4.1 tensorflow-estimator-2.4.0 wheel-0.36.2 wrapt-1.12.1
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: six in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (1.15.0)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: numpy in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (1.19.5)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: protobuf>=3.6.1 in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (3.15.8)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: wrapt in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.1)
Requirement already satisfied: absl-py in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (0.12.0)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Note: you may need to restart the kernel to use updated packages.
In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
from PIL import Image
import warnings
warnings.filterwarnings('ignore')
In [2]:
# TODO: Make all other necessary imports.
%matplotlib inline
%config InlineBackend.figure_format="retina"
import matplotlib.pyplot as plt
import numpy as np

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [3]:
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102

# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
#tfds.download.DownloadConfig(register_checksums=True);
dataset, dataset_info= tfds.load("oxford_flowers102", as_supervised=True, with_info=True)
2021-05-01 05:37:48.857652: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-05-01 05:37:48.857707: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
usage: download_and_prepare.py build [-h] [--helpfull]
                                     [--module_import MODULE_IMPORT]
                                     [--builder_config_id BUILDER_CONFIG_ID]
                                     [--datasets DATASETS_KEYWORD [DATASETS_KEYWORD ...]]
                                     [--overwrite]
                                     [--max_examples_per_split [MAX_EXAMPLES_PER_SPLIT]]
                                     [--data_dir DATA_DIR]
                                     [--download_dir DOWNLOAD_DIR]
                                     [--extract_dir EXTRACT_DIR]
                                     [--manual_dir MANUAL_DIR]
                                     [--add_name_to_manual_dir]
                                     [--config CONFIG]
                                     [--config_idx CONFIG_IDX]
                                     [--imports IMPORTS]
                                     [--register_checksums]
                                     [--force_checksums_validation]
                                     [--beam_pipeline_options BEAM_PIPELINE_OPTIONS]
                                     [--exclude_datasets EXCLUDE_DATASETS]
                                     [--experimental_latest_version]
                                     [datasets [datasets ...]]
download_and_prepare.py build: error: argument --register_checksums: ignored explicit argument 'True'
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1...


Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.
In [5]:
# TODO: Create a training set, a validation set and a test set.
validation_set= dataset["validation"]
training_set= dataset["train"]
test_set=dataset["test"]

Explore the Dataset

In [6]:
dataset_info
Out[6]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
    in the United Kingdom. Each class consists of between 40 and 258 images. The images have
    large scale, pose and light variations. In addition, there are categories that have large
    variations within the category and several very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set.
    The training set and validation set each consist of 10 images per class (totalling 1020 images each).
    The test set consists of the remaining 6149 images (minimum 20 per class).
    
    Note: The dataset by default comes with a test size larger than the train
    size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_path='/root/tensorflow_datasets/oxford_flowers102/2.1.1',
    download_size=328.90 MiB,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)
In [7]:
# TODO: Get the number of examples in each set from the dataset info.
total_val=dataset_info.splits['validation'].num_examples
total_train=dataset_info.splits['train'].num_examples
total_test=dataset_info.splits['test'].num_examples

print("Total training set {:,}".format(total_train))
print("Total test set {:,}".format(total_test))
print("Total validation set {:,}".format(total_val))

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes=dataset_info.features['label'].num_classes
total_num_example= dataset_info.splits['train'].num_examples

shape_images= dataset_info.features['image'].shape
print('Number of images :',total_num_example)
print("Number of classes {:,}".format(num_classes))
Total training set 1,020
Total test set 6,149
Total validation set 1,020
Number of images : 1020
Number of classes 102
In [8]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
    image = image.numpy()
    label = label.numpy()

    plt.imshow(image)
    plt.show()
    print('The shape of this image is:', image.shape)
    print('The label of this image is:', label)
The shape of this image is: (500, 667, 3)
The label of this image is: 72
The shape of this image is: (500, 666, 3)
The label of this image is: 84
The shape of this image is: (670, 500, 3)
The label of this image is: 70
In [9]:
# TODO: Plot 1 image from the training set. 
# Set the title of the plot to the corresponding image label. 
fig, (ax1) = plt.subplots(figsize=(6,9), ncols=1)
ax1.imshow(image, cmap=plt.cm.binary)
ax1.axis('off')
ax1.set_title(label)
plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [10]:
import json
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [11]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
fig, (ax1) = plt.subplots(figsize=(6,9), ncols=1)
ax1.imshow(image, cmap=plt.cm.binary)
ax1.axis('off')
ax1.set_title(class_names[str(label+1)])
plt.show()

Create Pipeline

In [12]:
# TODO: Create a pipeline for each set.
batch_size=32
image_size=224
num_training_example = (total_num_example * total_train)//100
def normalize(image, label):
    image=tf.cast(image, tf.float32)
    image=tf.image.resize(image,(image_size, image_size))
    image/=255
    return image, label


training_batches= training_set.cache().shuffle(num_training_example//4).map(normalize).batch(batch_size).prefetch(1)
testing_batches= test_set.cache().map(normalize).batch(batch_size).prefetch(1)
validation_set_batches= validation_set.cache().map(normalize).batch(batch_size).prefetch(1)
validation_set
Out[12]:
<PrefetchDataset shapes: ((None, None, 3), ()), types: (tf.uint8, tf.int64)>

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [13]:
# TODO: Build and train your network.

url="https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(url, input_shape=(image_size, image_size,3))
feature_extractor.trainable=False

model=tf.keras.Sequential([feature_extractor, 
                          tf.keras.layers.Dense(102, activation='softmax')])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
EPOCHS=10
early_stopping= tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
history = model.fit(training_batches, epochs=EPOCHS, validation_data=validation_set_batches, callbacks=early_stopping)
Epoch 1/10
32/32 [==============================] - 52s 1s/step - loss: 4.5954 - accuracy: 0.0783 - val_loss: 3.0902 - val_accuracy: 0.3833
Epoch 2/10
32/32 [==============================] - 46s 1s/step - loss: 2.2901 - accuracy: 0.6467 - val_loss: 2.0316 - val_accuracy: 0.6265
Epoch 3/10
32/32 [==============================] - 45s 1s/step - loss: 1.2153 - accuracy: 0.8812 - val_loss: 1.5489 - val_accuracy: 0.7118
Epoch 4/10
32/32 [==============================] - 46s 1s/step - loss: 0.7010 - accuracy: 0.9411 - val_loss: 1.3130 - val_accuracy: 0.7549
Epoch 5/10
32/32 [==============================] - 46s 1s/step - loss: 0.4527 - accuracy: 0.9706 - val_loss: 1.1731 - val_accuracy: 0.7667
Epoch 6/10
32/32 [==============================] - 45s 1s/step - loss: 0.3258 - accuracy: 0.9934 - val_loss: 1.0741 - val_accuracy: 0.7863
Epoch 7/10
32/32 [==============================] - 46s 1s/step - loss: 0.2366 - accuracy: 0.9978 - val_loss: 1.0119 - val_accuracy: 0.7980
Epoch 8/10
32/32 [==============================] - 46s 1s/step - loss: 0.1941 - accuracy: 1.0000 - val_loss: 0.9626 - val_accuracy: 0.8000
Epoch 9/10
32/32 [==============================] - 46s 1s/step - loss: 0.1557 - accuracy: 1.0000 - val_loss: 0.9295 - val_accuracy: 0.8000
Epoch 10/10
32/32 [==============================] - 46s 1s/step - loss: 0.1175 - accuracy: 1.0000 - val_loss: 0.9025 - val_accuracy: 0.8078
In [14]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy= history.history['accuracy']
validation_accuracy=history.history['val_accuracy']
validation_loss= history.history['val_loss']
training_loss= history.history['loss']

epochs_range= range(EPOCHS)

plt.figure(figsize=(8,8))
plt.subplot(1,2,1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1,2,2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [15]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('Total test set loss: {:,.3f}, and accuracy: {:,.3f}'.format(loss, accuracy))
    
193/193 [==============================] - 148s 766ms/step - loss: 1.0198 - accuracy: 0.7687
Total test set loss: 1.020, and accuracy: 0.769

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [16]:
# TODO: Save your trained model as a Keras model.

model.save("./image_classifier_model.h5")

Load the Keras Model

Load the Keras model you saved above.

In [17]:
# TODO: Load the Keras model

reload_model=tf.keras.models.load_model('./image_classifier_model.h5', custom_objects={'KerasLayer':hub.KerasLayer})

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [18]:
# TODO: Create the process_image function

def process_image(img):
    img = np.squeeze(img)
    image = tf.image.resize(img, (image_size, image_size))
    
    image = (image/255)
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [19]:
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [20]:
# TODO: Create the predict function

def predict(image_path, model, top_k = 5):
    im = Image.open(image_path)
    predict_images = np.asarray(im)
    predict_images = process_image(predict_images)
    prediction = model.predict(np.expand_dims(predict_images, axis= 0))
    
    top_k_probs, top_k_classes = tf.nn.top_k(prediction, k=top_k)
    
    probs = top_k_probs.numpy()
    classes = top_k_classes.numpy()
    
    return probs, classes, predict_images

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [21]:
# TODO: Plot the input image along with the top 5 classes
def getflowerlabel(classes):
    flowers = []
    flower_classes = []
    for value in classes[0]:
        flower_classes.append(class_names[str(value+1)])
    flowers.append(flower_classes)
    return flowers

image_list = ["cautleya_spicata.jpg","hard-leaved_pocket_orchid.jpg","orange_dahlia.jpg","wild_pansy.jpg"]

for img in image_list:
    file_name = './test_images/' + img;
    flower= img.replace("_"," ").replace(".jpg","")
    probs, classes, im = predict(file_name, model)
    
    flowers=getflowerlabel(classes)

    fig, (ax1, ax2) = plt.subplots(figsize=(10,5), ncols=2)
    ax1.imshow(im)
    ax1.set_title('Predicted Image: {}'.format(flower))
    ax2.barh(flowers[0], probs[0])

    ax2.set_title('Top 5 predicted classes')

    plt.tight_layout()
    plt.show()
In [ ]: